package com.yuelan.codelib.utils;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;

import com.exmaple.baidumv.info.ConFigFile;
import com.yuelan.codelib.utils.encryption.MD5Encoder;

/**
 * 作者: peijiangping<BR>
 * 2013-2-19下午1:56:07<BR>
 * ImageDownloader.java<BR>
 * 功能:异步下载图片功能类<BR>
 */
public class ImageDownloader {
	private static Map<String, SoftReference<Bitmap>> imageCaches = new HashMap<String, SoftReference<Bitmap>>();
	private static Map<String, SoftReference<File>> fileCaches = new HashMap<String, SoftReference<File>>();
	/**
	 * 同时执行5个线程 最多200个排队。5秒超时 ,单位为秒 ，工作队列大小。
	 */
	private static ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 200,
			5, TimeUnit.SECONDS, new ArrayBlockingQueue(5),
			new ThreadPoolExecutor.DiscardOldestPolicy());
	private static final Map<String, List<OnImageDownload>> taskList = new HashMap<String, List<OnImageDownload>>();
	private static final Map<String, List<OnFileDownload>> taskList_file = new HashMap<String, List<OnFileDownload>>();

	/**
	 * 作者: peijiangping<BR>
	 * 时间:2013-2-19下午2:11:17<BR>
	 * 功能:<BR>
	 * 返回值:void<BR>
	 */
	public static void imageDownload(final String url, final Context c,
			final OnImageDownload download, final int size) {
		if (!TextUtil.notNull(url)) {
			return;
		}
		SoftReference<Bitmap> currBitmap = imageCaches.get(url);
		Bitmap bitmap = null;
		if (currBitmap != null) {
			bitmap = currBitmap.get();
		}
		if (currBitmap != null && bitmap != null) {
			download.onDownloadSucc((Bitmap) bitmap);
		} else {
			final Handler handler = new Handler() {
				public void handleMessage(Message message) {
					synchronized (taskList) {
						for (OnImageDownload mOnImageDownload : taskList
								.get(url))
							mOnImageDownload
									.onDownloadSucc((Bitmap) message.obj);
						taskList.remove(url);
					}
				}
			};
			synchronized (taskList) {
				if (taskList.containsKey(url)) {
					taskList.get(url).add(download);
				} else {
					taskList.put(url, new ArrayList<OnImageDownload>());
					taskList.get(url).add(download);
					// 用线程池来做下载图片的任务
					executor.execute(new Runnable() {
						@Override
						public void run() {
							Bitmap bitmap = loadImageFromUrl(c, url, size);
							imageCaches.put(url, new SoftReference<Bitmap>(
									bitmap));
							Message message = handler.obtainMessage(0, bitmap);
							handler.sendMessage(message);
						}
					});
				}
			}
		}
	}

	/**
	 * 作者: peijiangping<BR>
	 * 时间:2013-2-19下午2:11:17<BR>
	 * 功能:<BR>
	 * 返回值:void<BR>
	 */
	public static void imagesDownload(final ArrayList<String> urls,
			final Context c, final OnImagesDownload download, final int size) {
		if (urls == null || urls.size() <= 0) {
			return;
		}
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				download.onDownloadSucc((ArrayList<Bitmap>) message.obj);
			}
		};
		executor.execute(new Runnable() {
			@Override
			public void run() {
				ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
				for (int i = 0; i < urls.size(); i++) {
					Bitmap bitmap = loadImageFromUrl(c, urls.get(i), size);
					bitmaps.add(bitmap);
				}
				Message message = handler.obtainMessage(0, bitmaps);
				handler.sendMessage(message);
			}
		});
	}

	/**
	 * 作者: peijiangping<BR>
	 * 时间:2013-2-19下午2:11:17<BR>
	 * 功能:<BR>
	 * 返回值:void<BR>
	 */
	public static void fileDownload(final String url, final Context c,
			final OnFileDownload download) {
		if (!TextUtil.notNull(url)) {
			return;
		}
		SoftReference<File> currFile = fileCaches.get(url);
		File file = null;
		if (currFile != null) {
			file = currFile.get();
		}
		if (fileCaches != null && file != null) {
			download.onDownloadSucc((File) file, url);
		} else {
			final Handler handler = new Handler() {
				public void handleMessage(Message message) {
					synchronized (taskList_file) {
						for (OnFileDownload download : taskList_file.get(url))
							download.onDownloadSucc((File) message.obj, url);
						taskList_file.remove(url);
					}
				}
			};
			synchronized (taskList_file) {
				if (taskList_file.containsKey(url)) {
					taskList_file.get(url).add(download);
				} else {
					taskList_file.put(url, new ArrayList<OnFileDownload>());
					taskList_file.get(url).add(download);
					// 用线程池来做下载图片的任务
					executor.execute(new Runnable() {
						@Override
						public void run() {
							File file = loadFileFromUrl(c, url);
							fileCaches.put(url, new SoftReference<File>(file));
							Message message = handler.obtainMessage(0, file);
							handler.sendMessage(message);
						}
					});
				}
			}
		}
	}

	/**
	 * Role:下载到缓存<BR>
	 * Date:2012-5-3<BR>
	 * 
	 * @author ZHENSHI)peijiangping
	 */
	public static Bitmap loadImageFromUrl(Context context, String imageUrl,
			int size) {
		File file = null;
		Bitmap bitmap = null;
		String fileName = MD5Encoder.EncoderByMd5(imageUrl);
		if (SDCardUtil.canUserSDCard(1024 * 1024)) {
			file = new File(ConFigFile.getSD_Picture(context) + "/" + fileName);
		} else {
			file = new File(context.getCacheDir(), fileName);
		}
		if (file.exists()) {
			bitmap = BitmapUtil.readBitmapForBig(file.toString(), size);
			if (bitmap == null) {
				int value = HttpConnent.download(imageUrl, file, 0);
				if (value == 1) {
					bitmap = BitmapUtil.readBitmapForBig(file.toString(), size);
				} else {
					file.delete();
				}
			}
		} else {
			int value = HttpConnent.download(imageUrl, file, 0);
			if (value == 1) {
				bitmap = BitmapUtil.readBitmapForBig(file.toString(), size);
			} else {
				file.delete();
			}
		}
		return bitmap;
	}

	/**
	 * Role:下载到缓存<BR>
	 * Date:2012-5-3<BR>
	 * 
	 * @author ZHENSHI)peijiangping
	 */
	public static File loadFileFromUrl(Context context, String fileUrl) {
		File file = null;
		String fileName = MD5Encoder.EncoderByMd5(fileUrl);
		if (SDCardUtil.canUserSDCard(1024 * 1024)) {
			file = new File(ConFigFile.getSD_Picture(context) + "/" + fileName);
		} else {
			file = new File(context.getCacheDir(), fileName);
		}
		if (!file.exists()) {
			int value = HttpConnent.download(fileUrl, file, 0);
			if (value != 1) {
				file.delete();
			}
		}
		return file;
	}

	public interface OnImageDownload {
		public void onDownloadSucc(Bitmap bitmap);
	}

	public interface OnImagesDownload {
		public void onDownloadSucc(ArrayList<Bitmap> bitmaps);
	}

	public interface OnFileDownload {
		public void onDownloadSucc(File file, String imageUrl);
	}

	public static File loadImageViewForFile(String imageUrl, Context c) {
		File file = null;
		if (TextUtil.notNull(imageUrl)) {
			String fileName = MD5Encoder.EncoderByMd5(imageUrl);
			if (SDCardUtil.hasStorage()) {
				file = new File(ConFigFile.getSD_Picture(c) + "/" + fileName);
			} else {
				file = new File(c.getCacheDir(), fileName);
			}
		}
		return file;
	}

	// private static String getSD_Picture(Context c) {
	// String SD_Path = SDCardUtil.getSDCardPath();
	// String SD_AppPath = SD_Path + "/TCJY/";
	// return SD_AppPath + "picture";
	// }
}
